package com.nd.android.musicboxlibrary.ui.vip;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.common.widget.CommonActivityTitle;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.BuyVipFailureException;
import com.nd.android.musicboxlibrary.business.comm.ResponseCallback;
import com.nd.android.musicboxlibrary.business.comm.ThreadUtil;
import com.nd.android.musicboxlibrary.ui.common.BaseFragmentActivity;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.TypefaceUtil;

public class VipIntroduceActivity extends BaseFragmentActivity implements RenewVipConfirmDialog.OnUserSelectListener {

	private CommonActivityTitle mCommonTitle;
	
	private ViewGroup mLayoutRoot;
	
	private ImageView mImgBg;
	private Button mBtnRegistVip99;
	private Button mBtnRegistVip19;

    private RenewVipConfirmDialog mRenewDialog;

	private ProgressDialog mProgressDialog;

    private static enum VipType {
		MONTH( 570001, R.string.mbx_vip_introduce_name_month, 19 ),
		YEAR( 570012, R.string.mbx_vip_introduce_name_year, 99 );

		public int type;
        public int nane_ref;
		public int price;
		
		VipType(int type, int nameRef, int price) {
			this.type = type;
            this.nane_ref = nameRef;
			this.price = price;
		}
	}
	private VipType mVipType;
	
	private int mCurrentDiamondRemain;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView( R.layout.mbx_vip_introduce_activity );
		
		setupViews();
	}
	
	private void setupViews() {
		mLayoutRoot = (ViewGroup) findViewById( R.id.layout_root );
		
		mCommonTitle = (CommonActivityTitle) findViewById( R.id.common_title );
		mCommonTitle.setTitleBtnCallback( new CommonActivityTitle.TitleBtnCallback() {
			@Override
			public void onBtnClick(int clickType) {
				switch ( clickType ) {
				case CommonActivityTitle.ON_LEFT_CLICK_CALL_BACK:
					finish();
					break;
				default:
					break;
				}
			}
		});
		
		mImgBg = (ImageView) findViewById( R.id.img_bg );
		mImgBg.post( new Runnable() {
			@Override
			public void run() {
				final int screenWidth = getResources().getDisplayMetrics().widthPixels;
				Drawable img = getResources().getDrawable( R.drawable.mbx_vip_introduce_activity_bg );
				final int imgHeight = img.getIntrinsicHeight() / img.getIntrinsicWidth() * screenWidth;
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( screenWidth, imgHeight );
				lp.addRule( RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE );
				mImgBg.setLayoutParams( lp );
			}
		} );
		
		mBtnRegistVip99 = (Button) findViewById( R.id.btn_vip_99 );
		mBtnRegistVip99.setOnClickListener( this );
		mBtnRegistVip19 = (Button) findViewById( R.id.btn_vip_19 );
		mBtnRegistVip19.setOnClickListener( this );
		
		TypefaceUtil.setFontRecursion( mLayoutRoot );
	}
	
	@Override
	public void onClick(View v) {
		if ( v == mBtnRegistVip99 ) {
			mVipType = VipType.YEAR;
            waitToComfirm();

		} else if ( v == mBtnRegistVip19 ) {
			mVipType = VipType.MONTH;
            waitToComfirm();

		}
	}


    private void waitToComfirm() {
        if ( mRenewDialog == null ) {
            mRenewDialog = new RenewVipConfirmDialog( this );
            mRenewDialog.setUserSelectListener( this );
        }

        final String name = String.format( getString( R.string.mbx_vip_renew_dialog_desc_name ),
                getString( mVipType.nane_ref ) );

        final String price = String.format( getString( R.string.mbx_vip_renew_dialog_desc_diamond ),
                String.valueOf( mVipType.price ) );

        mRenewDialog.setupInfos( name, price );
        mRenewDialog.show();
    }

    @Override
    public void onConfirm() {
        payToRecharge();
    }

    @Override
    public void onCancel() {

    }

	/**
	 * 开通VIP服务
	 * @author 			DingXiaohui
	 * @date 				2014-11-21 上午10:28:13
	 * @description
	 */
	private void payToRecharge() {
		final int price = mVipType.price;

		if ( mProgressDialog == null ) {
			mProgressDialog = new ProgressDialog( this );
			mProgressDialog.setMessage(getString(R.string.mbx_vip_please_wait));
		}
		mProgressDialog.show();

		ThreadUtil.executeMore( new Runnable() {
			@Override
			public void run() {
				// 获取当前用户星钻个数
				VipOperationWrapper.getVipDiamondRemain( getApplicationContext(), new ResponseCallback() {
					@Override
					public void onSuccess(Message msg) {
						mCurrentDiamondRemain = msg.what;
						Log.i( "David","VIP开通调试 :: 用户当前剩余 星钻-->" + mCurrentDiamondRemain );
						final int realPrice = Math.max( price - mCurrentDiamondRemain, 0 );
						if ( realPrice == 0 ) {
							// 无需充值;
							runOnUiThread( new Runnable() {
								@Override
								public void run() {
									renewVIP();
								}
							} );

						} else {
							// 登录支付页面
							runOnUiThread( new Runnable() {
								@Override
								public void run() {
//									loginAndPayIfNeed( realPrice );
//                                    openCommonRechargeDialog();
                                    pay( VipIntroduceActivity.this, realPrice );
                                }
							} );

						}
					}

					@Override
					public void onFailed(Exception exception) {
						// 获取当前星钻数量失败（网络异常）
						postToastWhenFailure();

					}
				} );
			}
		} );

        // 测试代码，直接开通VIP
//        renewVIP();

	}

	/**
	 * 登陆支付系统后 打开支付页面
	 * @author 			DingXiaohui
	 * @date 				2014-11-21 上午10:27:40
	 * @description
	 * @param activity
	 * @param cost
	 */
	private void pay(final Activity activity, final int cost) {

	}

	/**
	 * 开通VIP并消耗星钻
	 * @author 			DingXiaohui
	 * @date 				2014-11-19 下午5:32:24
	 * @description
	 */
	private void renewVIP() {
		final Context context = this;
		final String guid = "";
		ThreadUtil.executeMore( new Runnable() {
			@Override
			public void run() {
				VipOperationWrapper.renewVip( VipIntroduceActivity.this, mVipType.type, guid, new ResponseCallback() {
					@Override
					public void onSuccess(Message msg) {
						runOnUiThread( new Runnable() {
							@Override
							public void run() {
								// VIP开通成功
								VipOperationWrapper.markVipNotifyIntercepted( context, false );
								VipOperationWrapper.asyncUpdateVipInfo( context );
								Toast.makeText( context, getString( R.string.mbx_vip_renew_successful ), Toast.LENGTH_SHORT ).show();
								finish();

								if ( mProgressDialog != null ) {
                                    mProgressDialog.dismiss();
								}
							}
						} );
					}
					@Override
					public void onFailed(Exception exception) {
						// VIP开通失败
                        if ( exception instanceof BuyVipFailureException ) {
                            // 购买异常
                            final String msg = ((BuyVipFailureException)exception).msg;
                            if ( !TextUtils.isEmpty( msg ) ) {
                                postToastWhenFailure( msg );
                            } else {
                                postToastWhenFailure();
                            }
                        } else {
                            // 其他异常
                            postToastWhenFailure();
                        }

					}
				});
			}
		} );
	}

    private void postToastWhenFailure(final String msg) {
        runOnUiThread( new Runnable() {
            @Override
            public void run() {
                Toast.makeText( VipIntroduceActivity.this, msg, Toast.LENGTH_SHORT ).show();
                if ( mProgressDialog != null ) {
                    mProgressDialog.dismiss();
                }
            }
        } );
    }

	private void postToastWhenFailure() {
		postToastWhenFailure( getString( R.string.mbx_vip_network_failure_please_wait ) );
	}

    /***********************************************************************************/
    /**
     * 这下面都不要管
     */

//    private void openCommonRechargeDialog() {
//        CommonRechargeDlg dialog = new CommonRechargeDlg( this, new CommonBuyDiamond(
//                this, new ICommonBuyCallBack() {
//            @Override
//            public void onFail(String msg) {
//                postToastWhenFailure();
//            }
//
//            @Override
//            public void onSuccess(int diamondCount, int goldCount) {
//                renewVIP();
//            }
//        }
//        ));
//        dialog.show();
//    }


    //	/**
//	 * 登录支付系统
//	 * @author 			DingXiaohui
//	 * @date 				2014-11-21 上午10:28:04
//	 * @description
//	 * @param cost
//	 */
//	private void loginAndPayIfNeed(final int cost) {
//		final Activity activity = this;
//
//		if (!NdCommplatform.getInstance().isLogined()) {
//			NdCommplatform.getInstance().ndLogin(activity,
//					new NdMiscCallbackListener.OnLoginProcessListener() {
//						@Override
//						public void finishLoginProcess(int code) {
//							String tip = "";
//
//							boolean success = false;
//
//							// 登录的返回码检查
//							if (code == NdErrorCode.ND_COM_PLATFORM_SUCCESS) {
//								// String s = NdCommplatform.getInstance().getSessionId();
//								if (NdCommplatform.getInstance()
//										.ndGetLoginStatus() == NdLoginStatus.AccountLogin) {// 帐号登录
//									tip = "帐号登录成功";
//
//									pay( activity, cost );
//									success = true;
//
//								} else if (NdCommplatform.getInstance()
//										.ndGetLoginStatus() == NdLoginStatus.GuestLogin) {// 游客登录
//									tip = "游客登录成功";
//								}
//
//							} else if (code == NdErrorCode.ND_COM_PLATFORM_ERROR_CANCEL) {
//								tip = "取消帐号登录";
//
//							} else {
//								tip = "登录失败，错误代码：" + code;
//							}
//
//							Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
//
//							// 登录支付系统失败
//							if ( !success && mDialog != null ) {
//								mDialog.dismiss();
//							}
//						}
//					});
//		}
//
//		if (NdCommplatform.getInstance().ndGetLoginStatus() == NdLoginStatus.GuestLogin) {
//			NdCommplatform.getInstance().ndGuestRegist(this,
//					"您现在处于游客模式，为了更好地保护您的数据，请注册91通行证",
//					new NdMiscCallbackListener.OnLoginProcessListener() {
//						@Override
//						public void finishLoginProcess(int code) {
//							String tip = "";
//							switch (code) {// 登录的返回码检查
//							case NdErrorCode.ND_COM_GUEST_OFFICIAL_SUCCESS:
//								tip = "游客转正注册成功";
//								break;
//							case NdErrorCode.ND_COM_PLATFORM_SUCCESS:
//								tip = "游客使用已有帐号登陆成功";
//								break;
//							case NdErrorCode.ND_COM_PLATFORM_ERROR_CANCEL:
//								tip = "取消转正或者登录操作";
//								break;
//							default:
//								tip = "转正或者登录失败，错误代码：" + code;
//							}
//							Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show();
//
//							// 不明情况（取消等待对话框）
//							if ( mDialog != null ) {
//								mDialog.dismiss();
//							}
//						}
//					});
//		}
//
//		if (PaymentUtils.is91SDKLogin(activity)
//				&& NdCommplatform.getInstance().ndGetLoginStatus() == NdLoginStatus.AccountLogin) {
//			pay(activity, cost);
//		}
//	}
}
